package com.loongtech.bi.support;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthorityFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
      //  ((HttpServletResponse) response).sendRedirect("/resources/pages/realTime/platformAndChannelRealTime.jsf");

		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		Object userId = session.getAttribute("userId");
		String url = req.getRequestURI();

        // 集成部署和rest请求
        if (url.contains("cid.jsf") || url.contains("serverOnlineNum.jsf") || url.contains("/rest/")) {
            fc.doFilter(request, response);
            return;
        }

        String username = request.getParameter("uname");
        String password = request.getParameter("sign");
        String time = request.getParameter("time");

        if (username != null) {
            session.setAttribute("redirectusername", username);
            session.setAttribute("redirectpassword", password);
            session.setAttribute("redirecttime", time);
        }

		if(!url.contains("login.jsf") && userId == null) {
			((HttpServletResponse) response).sendRedirect("login.jsf");
		} else {
            if (StringUtils.isNotEmpty(url) && !url.contains("login.jsf") && !url.contains("left.jsf") && !url.contains("main.jsf")) {
                url = url.replace("/resources/pages/", "");
                session.setAttribute("lastURL", url);
            }
			fc.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
